<?php

class User extends BaseOrm {
	public $Type = 'User';

	public function Id() {
		return $this->Values['id'];
	}

	public function Dname() {
		return $this->Values['dname'];
	}

	public function Url() {
		return 'Users/' . $this->Values['urlname'];
	}

	public function Validate($password) {
		return (md5($password) == $this->Values['pswd']);
	}

	private $_favorites;
	public function Favorites() {
		if ( $this->_favorites ) return $this->_favorites;
		$favorites = new SmileyList();
		$favorites->SetValuesByFavorites($this->Values['id']);
		$this->_favorites = $favorites;
		// TODO offset and limit
		return $this->_favorites;
	}

	public function SetValuesById($id) {
		$query = "
			SELECT
				" . $this->EssentialColumns() . "
			FROM
				" . $this->TableName . " AS " . $this->TableAlias . "
			WHERE
				" . $this->PrimaryColumn . "=" . intval($id) . "
				AND enabled=1
			LIMIT
				1
		";

		return $this->_set($query);
	}

	public function SetValuesByUrlname($urldname) {
		$query = "
			SELECT
				" . $this->EssentialColumns() . "
			FROM
				" . $this->TableName() . " AS " . $this->TableAlias() . "
			WHERE
				urlname='" . mysql_escape_string($urldname) . "'
				AND enabled=1
			LIMIT
				1
		";

		return $this->_set($query);
	}

	public function SetValuesByLogin($username) {
		$query = "
			SELECT
				" . $this->EssentialColumns() . "
			FROM
				" . $this->TableName() . " AS " . $this->TableAlias() . "
			WHERE
				dname='" . mysql_escape_string($username) . "'
				OR email='" . mysql_escape_string($username) . "'
			LIMIT
				1
			";

		return $this->_set($query);
	}
}